const express = require("express");
const multer = require("multer");
const path = require("path");
const { spawn } = require('child_process');
const qiniu = require('qiniu');

const app = express();

app.use("/uploads", express.static(path.join(__dirname, "uploads")));

// 自定义文件命名函数
const customFileName = (req, file, callback) => {
  const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
  const fileExtension = path.extname(file.originalname);
  file.filename = Buffer.from(file.originalname, "latin1").toString("utf8");
  const fileName = `${file.filename}-${uniqueSuffix}${fileExtension}`;
  callback(null, fileName);
};

// const storage = multer.diskStorage({
//   destination: "uploads/",
//   filename: (req, file, callback) => {
//     callback(null, file.originalname);
//   },
// });
const storage = multer.memoryStorage();

const upload = multer({
  storage,
  limits: { fileSize: 300 * 1024 * 1024 },
  fileFilter: (req, file, callback) => {
    // 执行文件重命名
    customFileName(req, file, (err, fileName) => {
      if (err) {
        callback(err);
      } else {
        file.originalname = Buffer.from(file.originalname, "latin1").toString("utf8");
        file.filename = Buffer.from(file.filename, "latin1").toString("utf8");
        callback(null, true);
      }
    });
  },
});

const accessKey = '9omq-WRnf8BBI4LootZ184AJLbxRrh5Ev4Xn4THp';
const secretKey = 'heKCRGr0gB6DjPaN8MksjKA2P7P26iy4c-CcKT62';
const bucket = 'junroushop';
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const config = new qiniu.conf.Config();
const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();

app.post("/file/upload/file", upload.single("file"), (req, res) => {
    req.setTimeout(600000);
    
    const file = req.file;
    
    // 设置文件存储路径
    const filePath = 'supplier/' + file.originalname;
    
    // 生成上传凭证
    const options = {
    scope: bucket + ':' + filePath,
    };
    
    const putPolicy = new qiniu.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);
    
    // 要执行的Python文件路径
    const pythonFilePath = './index.py';
    const fileName = encodeURIComponent(file.filename);
    
    // 上传文件
    formUploader.put(uploadToken, filePath, file.buffer, putExtra, (err, body, info) => {
    if (err) {
      console.error(err);
      return res.status(500).json({ error: '上传失败' });
    }
    const filePath = encodeURIComponent(body.key);
    console.log('body: ', filePath)
    
    // 使用spawn函数调用Python程序
    const pythonProcess = spawn('python3', [pythonFilePath, filePath]);
    
    // 监听Python程序的输出
    pythonProcess.stdout.on('data', (data) => {
        console.log(`Python程序输出：${data}`);
        res.json({
            code: 200,
            message: "文件上传成功",
            data: { fileUrl: filePath },
        });
    });
    
    // 监听Python程序的错误输出
    pythonProcess.stderr.on('data', (data) => {
        console.error(`Python程序错误输出：${data}`);
        
        res.json({
            code: -1,
            message: "文件上传失败，稍后再试"
        });
    });
    
    // 监听Python程序的退出事件
    pythonProcess.on('close', (code) => {
        console.log(`Python程序退出，退出码：${code}`);
    });
    });
});

app.listen(6111, (err) => {
  if (!err) console.log("app server start..");
});
